/**
 * Copyright (C) <2023> <Boundivore> <boundivore@foxmail.com>
 * <p>
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the Apache License, Version 2.0
 * as published by the Apache Software Foundation.
 * <p>
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * Apache License, Version 2.0 for more details.
 * <p>
 * You should have received a copy of the Apache License, Version 2.0
 * along with this program; if not, you can obtain a copy at
 * http://www.apache.org/licenses/LICENSE-2.0.
 */
import React, { FC, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import { t } from 'i18next';
import { Space, Button, Dropdown, Divider, Radio, Input } from 'antd';
import { DownloadOutlined } from '@ant-design/icons';
import type { MenuProps, RadioChangeEvent } from 'antd';
import RequestHttp from '@/api';
import APIConfig from '@/api/config';
import { NodeDetailVo } from '@/api/interface';
import { fuzzySearchFiles } from '@/utils/helper';

const { Search } = Input;
// 从 MenuProps 中提取 items 类型
type MenuItem = NonNullable<MenuProps['items']>[number];

// 使用交叉类型将 NodeDetailVo 合并到 MenuItem 中
type MergedTabItem = MenuItem & NodeDetailVo;

// 定义扩展后的 MenuProps 类型
type MergedMenuProps = {
	items: MergedTabItem[];
};
interface DownloadConfigProps {
	buttonText: string;
	downloadAll?: false;
	fileList: string;
}
const DownloadConfig: FC<DownloadConfigProps> = ({ buttonText, fileList }) => {
	const [searchParams] = useSearchParams();
	const id = searchParams.get('id') || '';
	const serviceName = searchParams.get('name') || '';
	const [dropDownItems, setDropDownItems] = useState<MenuProps['items']>([]);
	const [radioNodeId, setRadioNodeId] = useState<string>('');
	const [allNodeData, setAllNodeData] = useState<MergedMenuProps['items']>([]);
	const [hostnameArr, setHostnameArr] = useState<string[]>([]);

	const handleSearch = (text: string) => {
		const result = fuzzySearchFiles(hostnameArr, text);
		const filteredTabsData = allNodeData?.filter(node => result.includes(node.Hostname));
		setDropDownItems(filteredTabsData);
	};

	const onChange = (e: RadioChangeEvent) => {
		setRadioNodeId(e.target.value);
	};

	const downloadConfig = async () => {
		const api = APIConfig.download;
		const params = {
			ClusterId: id,
			NodeId: radioNodeId,
			ServiceName: serviceName,
			FilePathArr: fileList
		};
		try {
			// 参数验证
			if (!params.ClusterId || !params.NodeId || !params.ServiceName || !params.FilePathArr) {
				throw new Error('Missing required parameters');
			}

			// 使用URLSearchParams构建查询字符串
			const searchParams = new URLSearchParams(params);
			const downloadUrl = `${api}?${searchParams.toString()}`;

			// 创建下载链接
			const link = document.createElement('a');
			link.href = downloadUrl;

			// 触发下载
			document.body.appendChild(link);
			link.click();
			document.body.removeChild(link);
		} catch (error) {
			console.error('下载文件失败:', error);
		}
	};
	const showDownloadList = async () => {
		const api = APIConfig.nodeList;
		const params = {
			ClusterId: id
		};
		const data = await RequestHttp.get(api, { params });
		const {
			Data: { NodeDetailList }
		} = data;
		const hostnames: string[] = [];
		const transformedData =
			NodeDetailList.length &&
			NodeDetailList.map((item: NodeDetailVo) => {
				hostnames.push(item.Hostname);
				return {
					...item,
					key: item.NodeId,
					label: (
						<div
							onClick={e => {
								e.stopPropagation();
							}}
						>
							<Radio value={item.NodeId}>{item.Hostname}</Radio>
						</div>
					)
				};
			});
		setHostnameArr(hostnames);
		setDropDownItems(transformedData);
		setAllNodeData(transformedData);
	};
	return (
		<Dropdown
			menu={{
				items: dropDownItems
			}}
			placement="bottomRight"
			getPopupContainer={() => document.body}
			overlayStyle={{
				zIndex: 1000000
			}}
			dropdownRender={menu => (
				<div className="bg-white rounded-lg shadow-md max-h-[300px] max-w-[200px]">
					<Search
						placeholder={t('inputHostName')}
						allowClear
						onSearch={value => handleSearch(value)}
						onChange={e => handleSearch(e.target.value)}
					/>
					<Radio.Group onChange={onChange} value={radioNodeId}>
						{React.cloneElement(
							menu as React.ReactElement<{
								className: string;
							}>,
							{ className: 'shadow-none' }
						)}
					</Radio.Group>
					<Divider style={{ margin: 0 }} />
					<Space style={{ padding: 8 }}>
						<Button type="primary" onClick={downloadConfig} disabled={Boolean(!radioNodeId)}>
							确认下载
						</Button>
					</Space>
				</div>
			)}
		>
			<Button type="primary" onClick={showDownloadList} disabled={Boolean(!fileList.length)}>
				<Space>
					{buttonText}
					<DownloadOutlined />
				</Space>
			</Button>
		</Dropdown>
	);
};
export default DownloadConfig;
